//
//  ESTFollowUpRecordtHeaderView.m
//  ESTSCRMAPP
//
//  Created by 李贤立 on 2018/10/24.
//  Copyright © 2018年 Capfer. All rights reserved.
//

#import "ESTFollowUpRecordtHeaderView.h"
#define FollowUpRecordTextFieldWordsMax   15
#define FollowUpRecordTextViewWordsMax    200
@implementation ESTFollowUpRecordHeaderViewModel

@end

@interface ESTFollowUpRecordtHeaderView ()<UITextFieldDelegate, UITextViewDelegate>
/**
 *  左边标签
 */
@property(nonatomic, strong) TYZLabel *leftLabel;
/**
 *  右边View
 */
@property(nonatomic, strong) TYZView *rightView;
/**
 *  右边输入框
 */
@property(nonatomic, strong) TYZTextField *textField;
/**
 *  右边的输入View
 */
@property(nonatomic, strong) TYZTextView *textView;
/**
 *  开关
 */
@property(nonatomic, strong) UISwitch *mySwitch;
/**
 *  textView文字长度提示
 */
@property(nonatomic, strong) TYZLabel *smallLabel;
/**
 *  存储选择项的按钮
 */
@property(nonatomic, strong) NSArray<TYZButton *> *buttonArray;
/**
 *  底线
 */
@property(nonatomic, strong) TYZView *line;
@end

@implementation ESTFollowUpRecordtHeaderView

+ (instancetype)creatFollowUpRecordtHeaderView:(UITableView *)tableView {
    ESTFollowUpRecordtHeaderView *headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"ESTFollowUpRecordtHeaderView"];
    if (headerView == nil) {
        headerView = [[ESTFollowUpRecordtHeaderView alloc] initWithReuseIdentifier:@"ESTFollowUpRecordtHeaderView"];
    }
    return headerView;
}
- (instancetype)initWithReuseIdentifier:(NSString *)reuseIdentifier {
    if (self = [super initWithReuseIdentifier:reuseIdentifier]) {
        self.contentView.backgroundColor = TYZWhiteColor;
        // 左边标题
        TYZLabel *leftLabel = [[TYZLabel alloc] init];
        [self.contentView addSubview:leftLabel];
        [leftLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(self.contentView);
            make.left.equalTo(self.contentView).offset(10);
        }];
        leftLabel.textColor = TYZLightColor;
        leftLabel.font = FollowUpRecordHeaderViewFont;
        self.leftLabel = leftLabel;
        
        // 右边View
        TYZView *rightView = [[TYZView alloc] init];
        [self.contentView addSubview:rightView];
        [rightView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.bottom.equalTo(self.contentView);
            make.left.equalTo(self.contentView).offset(120);
            make.width.mas_equalTo(kWindowWidth - 130);
        }];
        self.rightView = rightView;
        
        TYZView *line = [[TYZView alloc] init];
        [self.contentView addSubview:line];
        [line mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.contentView).offset(10);
            make.centerX.bottom.equalTo(self.contentView);
            make.height.mas_equalTo(1);
        }];
        line.backgroundColor = ESTBackgroundColor;
        self.line = line;
    }
    return self;
}
- (void)setModel:(ESTFollowUpRecordHeaderViewModel *)model {
    _model = model;
    [self.rightView.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [obj removeFromSuperview];
    }];
    switch (model.headerViewType) {
        case FollowUpTableViewHeaderViewType_TextField:
            if (model.maxWords == 0) {
                model.maxWords = FollowUpRecordTextFieldWordsMax;
            }
            [self addTextFieldWithEnable:!model.isNotEnable];
            break;
        case FollowUpTableViewHeaderViewType_Options:
            [self addOption];
            break;
        case FollowUpTableViewHeaderViewType_SelectedBlock:
            [self addTextFieldWithEnable:NO];
            [self addRightArrow];
            break;
        case FollowUpTableViewHeaderViewType_Switch:
            [self addSwitch];
            break;
        case FollowUpTableViewHeaderViewType_TextView:
            if (model.maxWords == 0) {
                model.maxWords = FollowUpRecordTextViewWordsMax;
            }
            self.smallLabel.text = [NSString stringWithFormat:@"0/%ld", (long)model.maxWords];
            [self addTextView];
            break;
        default:
            break;
    }
    self.leftLabel.text = model.leftTitle;
    self.textField.placeholder = model.placeholder;
    self.textField.text = model.rightText;
    self.textField.tag = model.textFieldTag;
    self.mySwitch.on = model.switch_state;
    self.line.hidden = model.hiddenLine;
}
#pragma mark - 设置UI
- (void)addTextFieldWithEnable:(BOOL)enable {
    TYZTextField *textField = [[TYZTextField alloc] init];
    [self.rightView addSubview:textField];
    textField.borderStyle = UITextBorderStyleNone;
    [textField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.rightView);
    }];
    textField.clearButtonMode = UITextFieldViewModeWhileEditing;
    textField.font = FollowUpRecordHeaderViewFont;
    textField.returnKeyType = UIReturnKeyDone;
    textField.textColor = TYZBlackColor;
    textField.returnKeyType = self.model.returnKeyType == UIReturnKeyNext ? UIReturnKeyNext : UIReturnKeyDone;
    textField.keyboardType = self.model.keyboardType;
    textField.delegate = self;
    textField.enabled = enable;
    self.textField = textField;
    
    WEAKSELF
    [[NSNotificationCenter defaultCenter] addObserverForName:UITextFieldTextDidEndEditingNotification object:nil queue:[NSOperationQueue currentQueue] usingBlock:^(NSNotification * _Nonnull note) {
        TYZTextField *textField = (TYZTextField *)note.object;
        if (textField.tag == weakSelf.model.textFieldTag) {
            if (weakSelf.didComplementTextFieldBlock) {
                weakSelf.didComplementTextFieldBlock(textField.text);
            }
        }
    }];
}
- (void)addOption {
    if (self.model.optionArray.count < 2) return;
    NSMutableArray *arrM = [NSMutableArray arrayWithCapacity:self.model.optionArray.count];
    CGFloat width = self.model.optionArray.firstObject.length * 15 + 40;
    CGFloat height = 30;
    [self.model.optionArray enumerateObjectsUsingBlock:^(NSString * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        TYZButton *button = [[TYZButton alloc] init];
        [self.rightView addSubview:button];
        [button mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(self.rightView);
            make.left.equalTo(self.rightView).offset((width + 10) * idx);
            make.width.mas_equalTo(width);
            make.height.mas_equalTo(height);
        }];
        button.layer.masksToBounds = YES;
        button.layer.cornerRadius = height * 0.5;
        button.layer.borderColor = TYZLightMMColor.CGColor;
        button.titleLabel.font = self.leftLabel.font;
        [button setTitle:obj forState:UIControlStateNormal];
        button.tag = TAG_SIXTH_ACTIVITY_SELECTOPTIONTags + idx;
        [self setupOptionWithButton:button selected:idx == self.model.selectedNumber];
        [button addTarget:self action:@selector(didClickSelectedOptionButton:) forControlEvents:UIControlEventTouchUpInside];
        [arrM addObject:button];
    }];
    self.buttonArray = [arrM mutableCopy];
}
- (void)didClickSelectedOptionButton:(TYZButton *)button {
    [self.buttonArray enumerateObjectsUsingBlock:^(TYZButton * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [self setupOptionWithButton:obj selected:idx == button.tag - TAG_SIXTH_ACTIVITY_SELECTOPTIONTags];
    }];
    if (self.didSelectedOptionsBlock) {
        self.didSelectedOptionsBlock(button.tag - TAG_SIXTH_ACTIVITY_SELECTOPTIONTags, button.titleLabel.text);
    }
}
- (void)setupOptionWithButton:(TYZButton *)button selected:(BOOL)selected {
    if (selected) {
        [button setTitleColor:TYZWhiteColor forState:UIControlStateNormal];
        [button setBackgroundColor:ThemeColor];
        button.layer.borderWidth = 0.0;
    } else {
        [button setTitleColor:TYZLightColor forState:UIControlStateNormal];
        [button setBackgroundColor:TYZClearColor];
        button.layer.borderWidth = 1.0;
    }
}
- (void)addRightArrow {
    TYZImageView *iconView = [[TYZImageView alloc] initWithImage:[UIImage imageNamed:@"arrow_right_999"]];
    [self.rightView addSubview:iconView];
    [iconView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.rightView);
        make.right.equalTo(self.rightView);
        make.width.height.mas_equalTo(20);
    }];
    TYZButton *coverButton = [TYZButton buttonWithType:UIButtonTypeCustom];
    [self.rightView addSubview:coverButton];
    [coverButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.rightView);
    }];
    [coverButton addTarget:self action:@selector(didClickCoverButton) forControlEvents:UIControlEventTouchUpInside];
}
- (void)didClickCoverButton {
    if (self.didClickCoverBlock) {
        self.didClickCoverBlock();
    }
}
- (void)addSwitch {
    UISwitch *mySwitch = [[UISwitch alloc] init];
    [self.rightView addSubview:mySwitch];
    [mySwitch mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.rightView);
        make.right.equalTo(self.rightView);
    }];
    mySwitch.onTintColor = ThemeColor;
    [mySwitch addTarget:self action:@selector(didChangedSwitch:) forControlEvents:UIControlEventValueChanged];
    self.mySwitch = mySwitch;
}
- (void)didChangedSwitch:(UISwitch *)sender {
    if (self.didClickSwitchBlock) {
        self.didClickSwitchBlock(sender.on);
    }
}
- (void)addTextView {
    [self.leftLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.contentView).offset(15);
        make.left.equalTo(self.contentView).offset(10);
    }];
    TYZTextView *textView = [[TYZTextView alloc] init];
    [self.rightView addSubview:textView];
    [textView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.leftLabel).offset(-8);
        make.left.right.bottom.equalTo(self.rightView);
    }];
    textView.tag = TAG_SIXTH_ACTIVITY_FOLLOWUPTEXTVIEW;
    textView.font = FollowUpRecordHeaderViewFont;
    textView.textColor = TYZBlackColor;
    textView.delegate = self;
    self.textView = textView;
    
    [self addTextFieldWithEnable:NO];
    [self.textField mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.leftLabel);
        make.left.equalTo(self.rightView).offset(5);
    }];
    
    TYZLabel *smallLabel = [[TYZLabel alloc] init];
    [self.rightView addSubview:smallLabel];
    [smallLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.rightView);
        make.bottom.equalTo(self.rightView).offset(-10);
    }];
    smallLabel.textColor = TYZLightMColor;
    smallLabel.font = TYZFont(CoreInfo.fontSize * 0.6);
    smallLabel.text = [NSString stringWithFormat:@"0/%d", FollowUpRecordTextViewWordsMax];
    self.smallLabel = smallLabel;
    
    WEAKSELF
    [[NSNotificationCenter defaultCenter] addObserverForName:UITextViewTextDidChangeNotification object:nil queue:[NSOperationQueue currentQueue] usingBlock:^(NSNotification * _Nonnull note) {
        UITextView *textView = (UITextView *)note.object;
        if (textView.tag == TAG_SIXTH_ACTIVITY_FOLLOWUPTEXTVIEW) {
            NSInteger count = textView.text.length;
            if (count == 0) {
                weakSelf.textField.placeholder = weakSelf.model.placeholder;
            } else {
                weakSelf.textField.placeholder = @"";
            }
            weakSelf.smallLabel.text = [NSString stringWithFormat:@"%ld/%ld", (long)count, (long)weakSelf.model.maxWords];
        }
    }];
    [[NSNotificationCenter defaultCenter] addObserverForName:UITextViewTextDidEndEditingNotification object:nil queue:[NSOperationQueue currentQueue] usingBlock:^(NSNotification * _Nonnull note) {
        TYZTextView *textView = (TYZTextView *)note.object;
        if (textView.tag == TAG_SIXTH_ACTIVITY_FOLLOWUPTEXTVIEW) {
            if (weakSelf.didComplementTextFieldBlock) {
                weakSelf.didComplementTextFieldBlock(textView.text);
            }
        }
    }];
}
#pragma mark - UITextViewDelegate
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    // 获取键盘中发送事件（回车事件）
    if ([text isEqualToString:@"\n"]) {
        if (self.didComplementTextFieldBlock) {
            self.didComplementTextFieldBlock(textView.text);
        }
        [textView resignFirstResponder];
    }
    if (textView.text.length + text.length > self.model.maxWords) {
        return NO;
    }
    return YES;
}
#pragma mark - UITextFieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if ([string isEqualToString:@""]) {
        return YES;
    }
    if (textField.text.length + string.length > self.model.maxWords) {
        return NO;
    }
    return YES;
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    if (self.didComplementTextFieldBlock) {
        self.didComplementTextFieldBlock(textField.text);
    }
    return YES;
}
- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end
